package com.zheng.umbrella.web.controller;

import com.zheng.common.base.BaseController;
import com.zheng.common.constant.Constant;
import com.zheng.upms.dao.model.UpmsAgent;
import com.zheng.upms.dao.model.UpmsAgentExample;
import com.zheng.upms.rpc.api.UpmsApiService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 后台controller
 * Created by ZhangShuzheng on 2017/01/12.
 */
@Controller
@RequestMapping("/manage")
@Api(value = "后台控制器", description = "后台管理")
public class ManageController extends BaseController {

	private static final Logger LOGGER = LoggerFactory.getLogger(ManageController.class);
	@Autowired
	private UpmsApiService upmsApiService;
	/**
	 * 后台首页
	 * @return
	 */
	@ApiOperation(value = "后台首页")
	@RequestMapping(value = "/index", method = {RequestMethod.GET, RequestMethod.POST})
	public String index() {
		return "/manage/index.jsp";
	}

	@ApiOperation(value = "代理树列表")
	@RequiresPermissions("upms:agent:read")
	@RequestMapping(value = "/agentTree", method = {RequestMethod.GET, RequestMethod.POST})
	@ResponseBody
	public Object agentTree(
			@RequestParam(required = false) Integer id) {
		UpmsAgentExample upmsAgentExample = new UpmsAgentExample();
		UpmsAgentExample.Criteria criteria = upmsAgentExample.createCriteria();
		criteria.andFlagEqualTo(Constant.CONST_FLAG_NORMAL);
		if (id!=null) {
			criteria.andPidEqualTo(id);
		}else{
			criteria.andPidIsNull();
		}
		List<UpmsAgent> rows = upmsApiService.selectUpmsAgentByExample(upmsAgentExample);
		List<HashMap<String, Object>> resultList = new ArrayList<HashMap<String, Object>>();
		for (UpmsAgent agent : rows) {
			HashMap<String, Object> tempMap = new HashMap<String, Object>();
			tempMap.put("id", agent.getId());
			tempMap.put("name", agent.getName());
			if (agent.getPid()!=null) {
				tempMap.put("pId", agent.getPid());
			}
//			tempMap.put("checked", agent.getIsAgent() ? "true":"false");
			tempMap.put("isParent", "true");
			tempMap.put("iconSkin", "");
			resultList.add(tempMap);
		}
		return resultList;
	}
}